// src\views\sendbox\audit-manage\Audit.jsx
// 审核新闻
import React, { useEffect, useState } from 'react'
import { Table, Button, Space,notification } from 'antd'
import axios from 'axios'
export default function Audit() {
  const [dataSource, setdataSource] = useState([])
  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author'
    },
    {
      title: "新闻分类",
      dataIndex: 'category',
      render: (category) => {
        return <div>{category.title}</div>
      }
    },
    {
      title: "操作",
      render: (item) => {
        return <Space>
          <Button type="primary" onClick={() => handleAudit(item, 2, 1)}>通过</Button>
          <Button danger onClick={() => handleAudit(item, 3, 0)}>驳回</Button>
        </Space>
      }
    }
  ];
  useEffect(() => {
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    axios.get(`http://localhost:8888/news?auditState=1&_expand=category`).then(res => {
      const list = res.data
      // 如果是超级管理员就渲染列表所有数据
      // 如果不是，只渲染自己新建的新闻或是自己区域的新闻且是有编辑权限的新闻
      setdataSource(roleObj[roleId] === "superadmin" ? list : [
        ...list.filter(item => item.author === username),
        ...list.filter(item => item.region === region && roleObj[item.roleId] === "editor")
      ])
    })
  }, [roleId, region, username]);
  const handleAudit = (item,auditState,publishState)=>{
    setdataSource(dataSource.filter(data=>data.id!==item.id))

    axios.patch(`http://localhost:8888/news/${item.id}`,{
        auditState,
        publishState
    }).then(res=>{
        notification.info({
            message: `通知`,
            description:
              `您可以到[审核管理/审核列表]中查看您的新闻的审核状态`,
            placement:"bottomRight"
        });
    })
}
  return (
    <div><Table dataSource={dataSource} columns={columns}
      pagination={{
        pageSize: 5
      }}

      rowKey={item => item.id}
    /></div>
  )
}
